package com.nuoniu.sibanyun.service.erp.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.erp.ErpProductionLine;
import com.nuoniu.sibanyun.mapper.erp.ErpProductionLineMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpProductionLineService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 生产线 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2020-12-30
 */
@Service
public class ErpProductionLineServiceImpl extends ServiceImpl<ErpProductionLineMapper, ErpProductionLine> implements IErpProductionLineService {

    @Autowired
    private IErpAccountService accountService;

    @Override
    public Page<ErpProductionLine> pageList(Page pages, ErpProductionLine productionLine) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<ErpProductionLine> wrapper = new QueryWrapper<>();
        wrapper.eq("company_id", userInfo.getCompanyId());
        wrapper.orderByAsc("code");
        return page(pages, wrapper);
    }

    @Override
    public void saveProductionLine(ErpProductionLine productionLine) {
        UserInfo userInfo = UserThreadLocal.get();
        ErpProductionLine lineByCode = baseMapper.getByCode(userInfo.getCompanyId(), productionLine.getCode());
        if(lineByCode != null && (productionLine.getId() == null || !productionLine.getId().equals(lineByCode.getId()))) {
            throw new NuoNiuException("生产线编码不能重复");
        }

        ErpProductionLine lineByName = baseMapper.getByName(userInfo.getCompanyId(), productionLine.getName());
        if(lineByName != null && (productionLine.getId() == null || !productionLine.getId().equals(lineByName.getId()))) {
            throw new NuoNiuException("生产线名称不能重复");
        }

        if(productionLine.getId() == null) {
            productionLine.setAccountId(accountService.getCurrentAccountId());
            productionLine.setCompanyId(userInfo.getCompanyId());
            productionLine.setCreateUserId(userInfo.getUserId());
            productionLine.setCreateUserName(userInfo.getRealName());
        }else {
            productionLine.setUpdateDate(LocalDateTime.now());
            productionLine.setUpdateUserId(userInfo.getUserId());
            productionLine.setUpdateUserName(userInfo.getRealName());
        }

        this.saveOrUpdate(productionLine);
    }
}
